<template>
  <div class="rule-apply-container">
    <div class="header">
      <h3>规则APPLY展示</h3>
      <p class="data-count">共 {{ props.applyData.length }} 条规则APPLY记录</p>
    </div>

    <!-- 如果没有数据 -->
    <div
      v-if="!props.applyData || props.applyData.length === 0"
      class="no-data"
    >
      <el-empty description="暂无规则应用数据">
        <el-icon><Document /></el-icon>
      </el-empty>
    </div>

    <!-- 数据展示区域 -->
    <div v-else class="data-container">
      <div
        v-for="(item, index) in props.applyData"
        :key="index"
        class="apply-item"
      >
        <!-- 标题：path + field -->
        <div class="item-header">
          <el-tag type="primary" size="large" class="path-tag">
            {{ item.path }}
          </el-tag>
          <el-divider direction="vertical" />
          <el-tag type="success" size="large" class="field-tag">
            {{ item.field }}
          </el-tag>
          <el-divider direction="vertical" />
          <span class="apply-count"
            >APPLY记录: {{ (item.apply || []).length }} 条</span
          >
        </div>

        <!-- Apply数据表格 -->
        <div class="table-container">
          <el-table
            :data="item.apply || []"
            stripe
            border
            size="small"
            :show-header="getTableColumns(item.apply).length > 0"
            empty-text="该规则无APPLY记录"
            class="apply-table"
          >
            <!-- 生成固定的列 -->
            <el-table-column
              v-for="column in getTableColumns(item.apply)"
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :min-width="column.minWidth"
              show-overflow-tooltip
            ></el-table-column>

            <!-- 如果没有列，显示原始数据 -->
            <el-table-column
              v-if="getTableColumns(item.apply).length === 0"
              label="原始数据"
            >
              <template #default="{ row, $index }">
                <el-tag size="small">第{{ $index + 1 }}项</el-tag>
                <el-tooltip :content="JSON.stringify(row, null, 2)">
                  <el-button type="text" size="small">
                    <el-icon><View /></el-icon>查看详情
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps } from "vue";
import { Document, View } from "@element-plus/icons-vue";

// 定义props
const props = defineProps({
  applyData: {
    type: Array,
    default: () => [],
    validator: (value) => {
      // 验证数组中的每个元素都有path、field、apply字段
      return value.every(
        (item) =>
          typeof item === "object" &&
          "path" in item &&
          "field" in item &&
          "apply" in item
      );
    },
  },
});

// 获取表格列配置
const getTableColumns = (applyArray) => {
  if (!applyArray || !Array.isArray(applyArray) || applyArray.length === 0) {
    return [];
  }

  // 收集所有可能的键
  const allKeys = new Set();
  applyArray.forEach((item) => {
    if (item && typeof item === "object") {
      Object.keys(item).forEach((key) => allKeys.add(key));
    }
  });

  // allKeys 排除 ord
  allKeys.delete("ord");

  // 键的顺序要按照以下：j_code, j_name, codes, names, med_codes, hsp_codes, hsp_names
  const preferredOrder = [
    "j_code",
    "j_name",
    "codes",
    "names",
    "med_codes",
    "hsp_codes",
    "hsp_names",
  ];

  // 转换为列配置
  preferredOrder.forEach((key) => {
    if (allKeys.has(key)) {
      allKeys.delete(key);
      allKeys.add(key); // 重新添加到末尾
    }
  });

  return Array.from(allKeys).map((key) => ({
    prop: key,
    label: formatColumnLabel(key),
    width: getColumnWidth(key),
    minWidth: getColumnMinWidth(key),
  }));
};

// 格式化列标题
const formatColumnLabel = (key) => {
  // 将驼峰命名转换为可读标题
  return key
    .replace(/([A-Z])/g, " $1")
    .replace(/^./, (str) => str.toUpperCase())
    .trim();
};

// 获取列宽度
const getColumnWidth = (key) => {
  const widthMap = {
    id: 80,
    index: 60,
    status: 80,
    type: 80,
    code: 100,
  };
  return widthMap[key] || null;
};

// 获取列最小宽度
const getColumnMinWidth = (key) => {
  const minWidthMap = {
    description: 200,
    content: 150,
    message: 150,
    detail: 200,
    name: 120,
    title: 120,
  };
  return minWidthMap[key] || 100;
};
</script>

<style scoped>
.rule-apply-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.data-count {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.data-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.apply-item {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.item-header {
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.path-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.field-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.apply-count {
  font-size: 14px;
  opacity: 0.9;
  margin-left: auto;
}

.table-container {
  padding: 0;
}

.apply-table {
  width: 100%;
}

.cell-content {
  word-break: break-word;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rule-apply-container {
    padding: 10px;
  }

  .item-header {
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
  }

  .apply-count {
    margin-left: 0;
    margin-top: 8px;
  }
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

/* 标签样式 */
:deep(.el-tag) {
  margin-right: 5px;
}

/* 分割线样式 */
:deep(.el-divider--vertical) {
  margin: 0 8px;
  background-color: rgba(255, 255, 255, 0.3);
}
</style>
